package mes

import (
	"context"
	"encoding/json"
	"ez/apps/mes/auto/mc"
	"gitee.com/dreamwood/ez-go/db/mgo"
	"gitee.com/dreamwood/ez-go/ez"
	"gitee.com/dreamwood/ez-go/ss"
	"time"
)

type Plan struct {
	mgo.BaseDoc `bson:"-" json:"-"`
	Id          int64 `json:"id" bson:"id,omitempty"`

	Sn string `json:"sn" bson:"sn"` //排产单号

	Product string `json:"product" bson:"product"` //产品名称

	NumNeed float64 `json:"numNeed" bson:"numNeed"` //排产数量

	NumDone float64 `json:"numDone" bson:"numDone"` //完成数量

	Template *ProcessTemplate `json:"template" bson:"template"` //应用模板

	TemplateId int64 `json:"templateId" bson:"templateId"` //应用模板

	PrintCount int64 `json:"printCount" bson:"printCount"` //打印量

	CreateAt time.Time  `json:"createAt" bson:"createAt"`
	UpdateAt time.Time  `json:"updateAt" bson:"updateAt"`
	DeleteAt *time.Time `json:"deleteAt" bson:"deleteAt"`
}

func (this *Plan) DocName() string { return "Plan" }

func (this *Plan) GetId() int64 { return this.Id }

func (this *Plan) SetId(id int64) { this.Id = id }

func (this *Plan) Create() error {
	return this.GetFactory().Create(this)
}

func (this *Plan) Replace() error {
	return this.GetFactory().Replace(this)
}

func (this *Plan) Save() error {
	if this.Id == 0 {
		this.CreateAt = time.Now()
		this.UpdateAt = time.Now()
		return this.GetFactory().Create(this)
	} else {
		this.UpdateAt = time.Now()
		return this.GetFactory().Replace(this)
	}
}

// 伪删除
func (this *Plan) Delete() error {
	return this.GetFactory().Delete(this)
}

func (this *Plan) UnDelete() error {
	return this.GetFactory().UnDelete(this)
}

// 真删除
func (this *Plan) Destroy() error {
	return this.GetFactory().Destroy(this)
}

func (this *Plan) ToString() string {
	return string(this.ToBytes())
}

func (this *Plan) ToBytes() []byte {
	data, e := json.Marshal(this)
	ez.Try(e)
	return data
}
func (this *Plan) Serialize() []byte {
	data, e := json.Marshal(this)
	ez.Try(e)
	return data
}
func (this *Plan) UnSerialize(data []byte) []byte {
	ez.Try(json.Unmarshal(data, this))
	return data
}

func (this *Plan) LoadTemplate() {
	if this.TemplateId == 0 {
		return
	}
	this.Template, _ = NewProcessTemplateCrud().FindId(this.TemplateId)
}

func (this *Plan) ClearRelationsBeforeSave() mgo.Doc {

	this.Template = nil

	return this
}

func neverUsed_Plan() {
	//导入ss包
	a := ss.M{}
	ez.Debug(a)
}

type PlanAccessControl struct {
	Access  bool
	Message string
	Action  string //控制器Action,小写开头，如c,u,r,d
	Model   *Plan
	Session *ez.Session
}

func NewPlanAccessControl(model *Plan, action string, session *ez.Session) *PlanAccessControl {
	ctrl := &PlanAccessControl{
		Access:  true,
		Model:   model,
		Action:  action,
		Session: session,
	}
	ez.DispatchToMany(mc.PlanAccessControlEvent, ctrl, context.TODO())
	return ctrl
}
